/**
 *  Module
 *
 * Description
 */
angular.
module('sfhtHaitaoCmsApp')
    .controller('ModalAddProductInfoCtrl', function($scope, $route, $injector, $modalInstance, listId, tabId, store) {
        var commonBizService = $injector.get("CommonBiz");
        var defaultSelected = {
            'key': "全部",
            'id': -1
        };
        $scope.hasMore = false;
        $scope.type = "";
        $scope.brands = [];
        $scope.brands.push(defaultSelected);
        $scope.secondCategorys = [];
        $scope.secondCategorys.push(defaultSelected);
        $scope.origins = [];
        $scope.origins.push(defaultSelected);
        $scope.selectBrand = defaultSelected.id;
        $scope.selectSecondCategory = defaultSelected.id;
        $scope.selectOrigin = defaultSelected.id;
        $scope.lastSearchKeywords = "";
        $scope.searchKeywords = "";
        $scope.curPageIndex = 1;
        $scope.productInfoList = [];
        String.prototype.replaceAll = function(s1, s2) {
            return this.replace(new RegExp(s1, "gm"), s2);
        };

        $scope.typeHolder = "";
        $scope.changeTypeValue = function(){
            if ($scope.type) {
                $scope.typeHolder = "多id使用','或' '分隔";
            }
            else{
                $scope.typeHolder = "";
            }
        }
        //查询操作
        $scope.search = function(searchKeywords, type, selectBrand, selectSecondCategory, selectOrigin, isFlip) {
            if (searchKeywords) {
                $scope.searchKeywords = searchKeywords;
            }
            if (selectBrand) {
                $scope.selectBrand = selectBrand;
            }
            if (selectSecondCategory) {
                $scope.selectSecondCategory = selectSecondCategory;
            }
            if (selectOrigin) {
                $scope.selectOrigin = selectOrigin;
            }
            if (!isFlip) {
                //非翻页操作将之前的搜索结果清空
                $scope.curPageIndex = 1;
                $scope.productInfoList = [];
            } else {
                $scope.curPageIndex = $scope.curPageIndex + 1;
            }
            //搜索条件发生变更
            var searchKeywordsChanged = $scope.lastSearchKeywords != searchKeywords;
            $scope.lastSearchKeywords = searchKeywords;
            if (searchKeywords) {
                type = type || "";
                if (type === "list" || type === "activity" || type === "item") {
                    searchKeywords = searchKeywords.replaceAll(" ", ",");
                }
                $scope.hasMore = false;
                commonBizService.getItems({
                        'searchKeywords': type == "" ? searchKeywords : (type + ":" + searchKeywords),
                        'brandId': $scope.selectBrand,
                        'secondCategoryId': $scope.selectSecondCategory,
                        'originId': $scope.selectOrigin,
                        'pageIndex': isFlip ? $scope.curPageIndex : 1,
                        'pageSize': 20
                    })
                    .then(function(data) {
                        if (data.value && data.value.length > 0) {
                            _.each(data.value, function(svalue, skey, slist) {
                                $scope.productInfoList.push(svalue);
                            });
                            if(data.value.length == 20){
                                $scope.hasMore = true;
                            }
                        } else {
                            alert('未搜索到数据，请重新输入');
                        }
                        $scope.canSave = $scope.productInfoList && $scope.productInfoList.length > 0;
                    }, function(data) {});
            }
        };

        /**
         * 全选还是反选
         * @param  {isSelectedAll} true:全选，false：反选
         * @return {array}
         */
        function selected(isSelectedAll) {
            if ($scope.productInfoList) {
                for (var i = 0; i < $scope.productInfoList.length; i++) {
                    if (isSelectedAll) {
                        $scope.productInfoList[i].checked = isSelectedAll;
                    } else {
                        $scope.productInfoList[i].checked = !$scope.productInfoList[i].checked;
                    }
                }
            }
        }
        //全选
        $scope.selectAll = function() {
                selected(true);
            }
            //反选
        $scope.selectInvert = function() {
            selected(false);
        }

        //是否售罄
        $scope.getStatusOfItem = function(info) {
            if (info) {
                return info._status;
            }
            return 0;
        };

        var convertToCMSDataProperty = function(productInfo, tabId) {
                var properties = [];
                for (var detail in productInfo) {
                    if (detail != "checked") {
                        properties.push({
                            "propertyName": detail,
                            "propertyValue": productInfo[detail]
                        });
                    }
                }

                if (typeof tabId != "undefined") {
                    properties.push({
                        "propertyName": "tag",
                        "propertyValue": tabId
                    });
                }
                properties["startTime"] = new Date().getTime();
                properties["endTime"] = new Date().getTime();
                return properties;
            }
            //新增保存
        $scope.save = function(productList, addToEnd) {
            var dataList = [];
            var addList = [];
            if (!productList || productList.length == 0) {
                alert("没有数据！！");
                return false;
            }
            _.filter(productList, function(productItem) {
                if (productItem.checked) {
                    addList.push(productItem);
                    var dataItem = {
                        listId: listId,
                        itemId: productItem.itemId,
                    };
                    dataItem.properties = convertToCMSDataProperty(productItem, tabId);
                    dataList.push(dataItem);
                }
            });

            commonBizService.addCmsData(dataList, addToEnd)
                .then(function(data) {
                    console.log(data);
                    $route.reload();
                    // window.location.reload(true);
                }, function(data) {
                    alert("添加失败，");
                    console.log(data);
                })

            $modalInstance.close(addList);
        };

        $scope.cancel = function() {
            $modalInstance.dismiss('cancel');
        };

        $scope.getChecked = function(productInfo, $event) {
            $event.preventDefault();
            productInfo.checked = !productInfo.checked;
        };
    });
